package com.atguigu.szdz.dcsyl.controller;

import com.atguigu.szdz.dcsyl.common.utils.R;
import com.atguigu.szdz.dcsyl.service.YlycService;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.commons.lang.StringUtils;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.*;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.*;

@RestController
@RequestMapping("/ylyc")
public class YlycController {
    @Value("${url}")
    String url;
    @Autowired
    private RestTemplate restTemplate;
    @Autowired
    private YlycService ylycService;

    @RequestMapping("/getYlycchartsList")
    public R getYlycchartsList() {

        List<Map<String, Object>> ylycAllList = ylycService.getYlycList();
        List<Map<String, Object>> ylycEchartsList = new ArrayList<>();
        for (Map<String, Object> map : ylycAllList) {
            Map<String, Object> map1 = new HashMap<>();
            double po = Double.parseDouble(String.valueOf(map.get("po")));
            double ph = Double.parseDouble(String.valueOf(map.get("ph")));
            double vo = Double.parseDouble(String.valueOf(map.get("vo")));
            double vn = Double.parseDouble(String.valueOf(map.get("vn")));
            double n = Double.parseDouble(String.valueOf(map.get("n")));


            double tg = Double.parseDouble(String.valueOf(map.get("tg")));
            double so = Double.parseDouble(String.valueOf(map.get("so")));
            double sh = Double.parseDouble(String.valueOf(map.get("sh")));
            double sh2 = Double.parseDouble(String.valueOf(map.get("sh2")));
            double arf = Double.parseDouble(String.valueOf(map.get("arf")));
            double uti = Double.parseDouble(String.valueOf(map.get("uti")));
            double depth = Double.parseDouble(String.valueOf(map.get("depth")));

            double pp = po - (po - ph) * Math.pow((vo / vn), n);
            double pc = (3 * sh - sh2 - 2 * so * tg + (Math.pow(tg, 2) - 1) * arf * pp) / (1 + Math.pow(tg, 2));
            double pf = 3 * sh2 - sh - arf * pp + uti;
            double lower = pc + 0.1;
            double upper = pf - 0.1;

            map1.put("pp", pp);
            map1.put("pc", pc);
            map1.put("pf", pf);
            map1.put("lower", lower);
            map1.put("upper", upper);

            map1.put("depth", depth);

            System.out.println("mmmmmmmmmmmmm:" + map1);

            ylycEchartsList.add(map1);
        }
        return R.ok().put("ylycEchartsList", ylycEchartsList);
    }

    @RequestMapping("/getYlycList")
    public R getYlycList(@RequestBody Map<String, Object> params) {
        Integer currentPage = (Integer) params.get("currentPage");
        String keyword = (String) params.get("keyword");

        if ((keyword != "") && (keyword.length() > 0)) {
            keyword
                    = " where (table_code like '%" + keyword + "%') or (well_name like '%"
                    + keyword + "%')";
        }

        List<Map<String, Object>> ylycList = ylycService.getYlycList(currentPage, keyword);
        List<Map<String, Object>> contList = ylycService.getCount("select count(*) from dc_ylyc" + keyword);
        Object count = contList.get(0).get("count");
        Long c = (Long) count;
        return R.ok().put("ylycList", ylycList).put("total", c);
    }

    //同步数据
    @PostMapping("/synData")
    @Transactional(rollbackFor = Exception.class)
    public void synData() {
        System.out.println("从数据服务同步数据!!!");

        // 创建HTTP头部
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);

        // 构建请求体
        Map<String, Object> subFilter = new HashMap<>();
        subFilter.put("symbol", "=");
        subFilter.put("singleValue", "WELLTL100001026");
        subFilter.put("logic", "AND");
        subFilter.put("key", "WELL_ID");

        Map<String, Object> anotherSubFilter = new HashMap<>();
        anotherSubFilter.put("symbol", "IN");
        anotherSubFilter.put("realValue", new String[]{"RT", "DEN", "SP", "GR", "P_AC", "CNL", "RMF", "AT20", "AT10", "SWW"});
        anotherSubFilter.put("logic", "AND");
        anotherSubFilter.put("key", "dataName");

        Map<String, Object> filter = new HashMap<>();
        filter.put("logic", "AND");
        filter.put("subFilter", new Object[]{subFilter, anotherSubFilter});

        Map<String, Object> query = new HashMap<>();
        query.put("filter", filter);

        Map<String, Object> requestBody = new HashMap<>();
        requestBody.put("pageNo", 1);
        requestBody.put("query", query);
        requestBody.put("pageSize", 10);
        requestBody.put("tableName", "X_CD_WELL_SOURCE");

        // 创建HttpEntity
        HttpEntity<Map<String, Object>> entity = new HttpEntity<>(requestBody, headers);

        // 发送POST请求
        ResponseEntity<String> exchange = restTemplate.exchange("http://" + url + "/ylyc/aaa",
                HttpMethod.POST, entity, String.class);
        String bodies = exchange.getBody();

        //解析返回数据
        ObjectMapper mapper = new ObjectMapper();
        String listString = "";
        try {
            JsonNode rootNode = mapper.readTree(bodies);
            JsonNode dataNode = rootNode.path("data");
            String data = dataNode.toString();
            rootNode = mapper.readTree(data);
            dataNode = rootNode.path("list");
            listString = dataNode.toString();
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }

        //如果无数据，直接结束
        if (listString.length() <= 0 || StringUtils.equals(listString, "")) {
            return;
        }

        //将数据转化为map集合
        JSONArray jsonArray = new JSONArray(String.valueOf(listString));
        List<Map<String, String>> list = new ArrayList<>();
        for (int i = 0; i < jsonArray.length(); i++) {
            JSONObject jsonObject = jsonArray.getJSONObject(i);
            Map<String, String> map = new HashMap<>();
            for (Object key : jsonObject.keySet()) {
                String v = String.valueOf(jsonObject.get((String) key));
                map.put((String) key, v);
            }
            list.add(map);
        }

        System.out.println("aaaaaaaaaaa:" + list);

//        List<Map<String, String>> mapList = new ArrayList<>();
//        for (Map<String, String> map : list) {
//            Map<String, String> map1 = new HashMap<>();
//            map1.put("well_name", map.get("well_name"));
//            map1.put("Po", map.get("Po"));
//            map1.put("Ph", map.get("Ph"));
//            map1.put("Vo", map.get("Vo"));
//            map1.put("Vn", map.get("Vn"));
//            map1.put("n", map.get("n"));
//            map1.put("SH", map.get("SH"));
//            map1.put("Sh", map.get("Sh"));
//            map1.put("So", map.get("So"));
//            map1.put("tg", map.get("tg"));
//            map1.put("arf", map.get("arf"));
//            map1.put("UTI", map.get("UTI"));
//            map1.put("depth", map.get("depth"));
//            mapList.add(map1);
//        }

        // 生成表单号
        String uuid = UUID.randomUUID().toString().replaceAll("-", "").substring(0, 12);
        String table_code = "T" + uuid;

        //更新预处理表数据
        ylycService.updateDate(table_code, list);
    }

    @PostMapping("/aaa")
    public String aaa(@RequestBody String aaa) {
        System.out.println("bbbbbbbbbbbbbbbbbbb!!!!!!!!!!!!:" + aaa);
        String json = "{\"code\":0,\"message\":\"操作处理成功\",\"data\":{\"total\":37,\"list\":[{\"well_name\":\"A1\",\"depth\":1110,\"lithology\":0.29,\"sound_waves\":0.29,\"density\":0.72,\"well_road\":0.16,\"natural_gamma\":1.36,\"natural_potential\":0.92,\"deep_resistivity\":0.67}" +
                ",{\"well_name\":\"A1\",\"depth\":1111,\"lithology\":0.30,\"sound_waves\":0.30,\"density\":0.73,\"well_road\":0.17,\"natural_gamma\":1.37,\"natural_potential\":0.93,\"deep_resistivity\":0.68}" +
                ",{\"well_name\":\"A1\",\"depth\":1112,\"lithology\":0.31,\"sound_waves\":0.31,\"density\":0.74,\"well_road\":0.18,\"natural_gamma\":1.38,\"natural_potential\":0.94,\"deep_resistivity\":0.69}" +
                ",{\"well_name\":\"A1\",\"depth\":1113,\"lithology\":0.32,\"sound_waves\":0.32,\"density\":0.75,\"well_road\":0.19,\"natural_gamma\":1.39,\"natural_potential\":0.95,\"deep_resistivity\":0.70}" +
                ",{\"well_name\":\"A1\",\"depth\":1114,\"lithology\":0.33,\"sound_waves\":0.33,\"density\":0.76,\"well_road\":0.20,\"natural_gamma\":1.40,\"natural_potential\":0.96,\"deep_resistivity\":0.71}" +
                ",{\"well_name\":\"A1\",\"depth\":1115,\"lithology\":0.34,\"sound_waves\":0.34,\"density\":0.77,\"well_road\":0.21,\"natural_gamma\":1.41,\"natural_potential\":0.97,\"deep_resistivity\":0.72}" +
                ",{\"well_name\":\"A1\",\"depth\":1116,\"lithology\":0.35,\"sound_waves\":0.35,\"density\":0.78,\"well_road\":0.22,\"natural_gamma\":1.42,\"natural_potential\":0.98,\"deep_resistivity\":0.73}" +
                ",{\"well_name\":\"A1\",\"depth\":1117,\"lithology\":0.36,\"sound_waves\":0.36,\"density\":0.79,\"well_road\":0.23,\"natural_gamma\":1.43,\"natural_potential\":0.99,\"deep_resistivity\":0.74}" +
                ",{\"well_name\":\"A1\",\"depth\":1118,\"lithology\":0.37,\"sound_waves\":0.37,\"density\":0.80,\"well_road\":0.24,\"natural_gamma\":1.44,\"natural_potential\":1.00,\"deep_resistivity\":0.75}" +
                ",{\"well_name\":\"A1\",\"depth\":1119,\"lithology\":0.38,\"sound_waves\":0.38,\"density\":0.81,\"well_road\":0.25,\"natural_gamma\":1.45,\"natural_potential\":1.01,\"deep_resistivity\":0.76}" +
                ",{\"well_name\":\"A1\",\"depth\":1120,\"lithology\":0.39,\"sound_waves\":0.39,\"density\":0.82,\"well_road\":0.26,\"natural_gamma\":1.46,\"natural_potential\":1.02,\"deep_resistivity\":0.77}" +
                ",{\"well_name\":\"A1\",\"depth\":1121,\"lithology\":0.40,\"sound_waves\":0.40,\"density\":0.83,\"well_road\":0.27,\"natural_gamma\":1.47,\"natural_potential\":1.03,\"deep_resistivity\":0.78}]}}";
        return json;
    }

}
